const path = require('path');
const buildutils = require('./buildutils');
const fs = require('fs')
const crypto = require('crypto')

function computeIntegrityHash(fullPath, algorithm = 'sha256'){
  const file = fs.readFileSync(fullPath);
  const hash = crypto.createHash(algorithm).update(file).digest('base64')
  return algorithm + '-' + hash;
}

function gulptasksHTML($, gulp, buildFolder, browserSync){
  const commitHash = buildutils.getRevision();

  async function buildHtml(
    {
      analytics = false,
      standalone = false,
      app = false,
      integrity = true,
    }
  ){
    const hasLocalFiles = standalone || app;

    return gulp
      .src('../src/html/' + ('index.html'))
      .pipe(
        $.dom(function(){
          const document = /** @type {Document} */ (this);

          // 添加css
          const css = document.createElement('link')
          css.rel = 'stylesheet'
          css.type = 'text/css'
          css.media = 'none'
          css.setAttribute("onload", 'this.media="all"');
          css.href = ('main.css')
          if(integrity){
            css.setAttribute(
              'integrity',
              computeIntegrityHash(path.join(buildFolder, 'main.css'))
            )
          }
          document.head.appendChild(css);

          if(analytics){
            // 不用谷歌的分析库，写完游戏后再加
            // const tagManagerScript = document.createElement('script')
            // tagManagerScript.src = 'https://www.googletagmanager.com/gtag/js?id=G-Z38F7FCXR1'
            // tagManagerScript.setAttribute('async', '')
            // document.head.appendChild(tagManagerScript)

            // const initScript = document.createElement('script')
            // initScript.textContent = `
            //   window.dataLayer = window.dataLayer || [];
            //   function gtag(){dataLayer.push(arguments);}
            //   gtag('js', new Date());
            
            //   gtag('config', 'G-Z38F7FCXR1');
            // `
            // document.head.appendChild(initScript)
          }

          // 不需要在APP或单机版中预加载资源
          // if(!hasLocalFiles){
            const preloads = ['fonts/GameFont.woff2', 'fonts/GameFont2.ttf', 'fonts/GameFont3.ttf'];

            preloads.forEach(src => {
              const preloadLink = document.createElement('link')
              preloadLink.rel = 'preload'
              preloadLink.href = ('res/' + src)
              if(src.endsWith('.woff2') || src.endsWith('.ttf')){
                preloadLink.setAttribute('crossorigin', 'anonymous')
                preloadLink.setAttribute('as', 'font')
              } else {
                preloadLink.setAttribute('as', 'image')
              }
              document.head.appendChild(preloadLink)
            })
          // }

          const loadingSvg = `background-image: url("")`;

          const loadingCss = `
          @font-face {
            font-family: 'GameFont';
            font-style: normal;
            font-weight: normal;
            font-display: swap;
            src: url('${("res/fonts/GameFont.woff2")}');
          }
          @font-face {
            font-family: 'GameFont2';
            font-style: normal;
            font-weight: normal;
            font-display: swap;
            src: url('${("res/fonts/GameFont2.ttf")}');
          }
          @font-face {
            font-family: 'GameFont3';
            font-style: normal;
            font-weight: normal;
            font-display: swap;
            src: url('${("res/fonts/GameFont3.ttf")}');
          }

          #ll_fp{
            font-family: 'GameFont';
            font-size: 14px;
            position: fixed;
            z-index: -1;
            top: 0;
            left: 0;
            opacity: .05;
          }

          #ll_p{
            display: flex;
            position: fixed;
            z-index: 99999;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            justify-content: center;
            align-items: center;
          }

          #ll_p > div{
            position: absolute;
            text-align: center;
            bottom: 40px;
            left: 20px;
            right: 20px;
            color: #393747;
            font-family: 'GameFont', sans-serif;
            font-size: 20px;
          }

          #ll_p > span{
            width: 60px;
            height: 60px;
            display: inline-flex;
            background: center center / contain no-repeat;
            ${loadingSvg}
          }
          `

          // 导入样式
          const style = document.createElement('style')
          style.setAttribute('type', 'text/css')
          style.textContent = loadingCss
          document.head.appendChild(style)

          // 加载最终打包后的bundle.js
          if(standalone){
            const bundleScript = document.createElement('script')
            bundleScript.type = 'text/javascript'
            bundleScript.src = 'bundle.js'
            if(integrity){
              bundleScript.setAttribute(
                'integrity',
                computeIntegrityHash(path.join(buildFolder, 'bundle.js'))
              )
            }
            document.head.appendChild(bundleScript)
          } else {
            const loadJs = document.createElement('script')
            loadJs.type = 'text/javascript'
            let scriptContent = "";
            scriptContent += `
              var bundleSrc = '${('bundle.js')}';
            `

            if(integrity){
              scriptContent += `
                var bundleIntegrity = '${computeIntegrityHash(path.join(buildFolder, 'bundle.js'))}';
              `
            } else {
              scriptContent += `
                var bundleIntegrity = null;
              `
            }

            scriptContent += fs.readFileSync('./bundle-loader.js').toString();
            loadJs.textContent = scriptContent;
            document.head.appendChild(loadJs)
          }

          const bodyContent = `
            <div id="ll_fp">_</div>
            <div id="ll_p">
              <span></span>
              <div>${hasLocalFiles ? '加载' : '下载'}游戏文件中</div>
            </div>
          `

          document.body.innerHTML = bodyContent;
        })
      )
      .pipe(
        $.htmlmin({
          caseSensitive: true,
          // 不删除元素间的所有空格将保留至一个
          collapseBooleanAttributes: true,
          collapseInlineTagWhitespace: true,
          collapseWhitespace: true,
          preserveLineBreaks: true,
          // end
          minifyJS: true,
          minifyCSS: true,
          quoteCharacter: '"',
          // 将空的属性值删除
          useShortDoctype: true,
        })
      )
      .pipe($.htmlBeautify())
      .pipe($.rename('index.html'))
      .pipe(gulp.dest(buildFolder))
  }

  gulp.task('html.dev', () => {
    return buildHtml({
      // 是否分析数据
      analytics: false,
      // 是否启用加密
      integrity: false,
    })
  })

  gulp.task("html.prod", () => {
		return buildHtml({
			// 是否分析数据
			analytics: true,
			// 是否启用加密
			integrity: false,
			standalone: true,
      app: true
		});
	});
}

module.exports = {
  gulptasksHTML
}